﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OreSystem.Entities;
using NHibernate;
namespace OreSystem.DAL
{
    public class CarDAL
    {
        public CarDAL()
        {

        }
        public IList<Car> GetAll()
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                return session.CreateQuery("from Car").List<Car>();
            }
        }

        public void Save(Car NewCar)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                session.SaveOrUpdate(NewCar);
                session.Flush();
            }
        }

        public Car GetCarById(int id)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                return session.Get<Car>(id);
            }
        }

        public void DeleteCar(Car car)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                session.Delete(car);
                session.Flush();
            }
        }

        public IList<Car> GetCarByType(int p)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
               return session.CreateQuery("from Car  c where c.Type=:type").SetInt32("type",p).List<Car>();
            }
        }

        public IList<Car> GetCarByTypeAndKeys(int type, string keys) {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                return session.CreateQuery("from Car c where c.Type=:type and c.CarNo like:keys").SetInt32("type",type).SetString("keys","%"+keys+"%").List<Car>();
            }
        }

        public void Deletes(IList<object> idlist)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                foreach (var item in idlist)
                {
                    var entity = session.Get<Car>(item);
                    if (entity !=null)
                    {
                        session.Delete(entity);                        
                    }
                }
                session.Flush();
            }
        }
    }
}
